// File AbstractLocation.cpp
//
// Purpose: abstract base class to define an interface for a state
//
// Author : Bryson King (edited)
// Original Code Provided by: Mat Buckland 2002 (fup@ai-junkie.com)
// Date : 18 March 2013
// --------------------------------------------------------------
#define DEBUG_SECTION

#include "AbstractLocation.h"

#include <map>
#include <string>
#include <typeinfo.h>

#include "GenericPerson.h"
#include "IPerson.h"
#include "Item.h"
#include "Player.h"
#include "Terrorist.h"

struct Telegram;

CLocation::CLocation() : m_iNumberOfPeopleInLocation(0), m_pHeadOfList(new entity_node())
{
	m_pTailOfList = m_pHeadOfList;
}

CLocation::~CLocation() {}

void CLocation::AddEntityToLocation(IPerson* entity)
{
	// Create the new node for the list
	entity_node* newNode = new entity_node();
	newNode->entity = entity;
	newNode->next = nullptr;

	// Add the node to the list
	m_pTailOfList->next = newNode;
	m_pTailOfList = newNode;

	m_iNumberOfPeopleInLocation++;
}

void CLocation::RemoveEntityFromLocation(IPerson* pEntity)
{
	entity_node* tempNode = m_pHeadOfList;
	entity_node* entityNode;

	// Search the list for the node to delete
	for (int i = 0; i < m_iNumberOfPeopleInLocation; i++)
	{
		if (tempNode->next->entity == pEntity)
		{
			entityNode = tempNode->next;
			if (entityNode == m_pTailOfList)
				m_pTailOfList = tempNode;
			tempNode->next = tempNode->next->next;
			entityNode->next = nullptr;
			delete entityNode;
		}
	}

	m_iNumberOfPeopleInLocation--;
}

IPerson* CLocation::RetrieveEntity(int index)
{
	entity_node* tempNode = m_pHeadOfList;

	// If the index is invalid, return a nullptr
	if (index >= m_iNumberOfPeopleInLocation)
		return nullptr;

	// Search the list for the node to return
	for (int i = 0; i <= index; i++)
	{
			tempNode = tempNode->next;
	}

	return tempNode->entity;
}

int CLocation::NumberOfPeopleAtLocation()
{
	return m_iNumberOfPeopleInLocation;
}

IPerson** CLocation::RetrieveAllEnemies(IPerson* pEntity, int& iNumberOfEnemies)
{
	IPerson** l_aReturnList = new IPerson*[];
	iNumberOfEnemies = 0;
	IPerson* l_pEntity;

	for (int i = 0; i < NumberOfPeopleAtLocation(); i++)
	{
		l_pEntity = RetrieveEntity(i);
		// Add enemy to the list
		if (typeid(pEntity) == typeid(l_pEntity))
			l_aReturnList[iNumberOfEnemies++] = l_pEntity;
		else if ((typeid(pEntity) == typeid(CPlayer)) && (typeid(l_pEntity) == typeid(CGenericPerson)))
			l_aReturnList[iNumberOfEnemies++] = l_pEntity;
	}

	return l_aReturnList;
}